﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace HenhouseEnvironmentCtrl
{
    public partial class HistoryForm : Form
    {
        public HistoryForm()
        {
            InitializeComponent();
        }

        private void HistoryForm_Load(object sender, EventArgs e)
        {
            dgvHistoryData.AutoGenerateColumns = true; // 确保 DataGridView 自动生成列
            LoadData();
            LoadHenhouseNames();
        }

        private void LoadData(string startDate = "", string endDate = "", string henhouseName = "")
        {
            try
            {
                using (SqlConnection conn = DBConnection.CreateConnection())
                {
                    DBConnection.Open(conn);
                    string query = "SELECT * FROM InternalEnvironment WHERE 1=1";
                    if (!string.IsNullOrEmpty(startDate)) query += $" AND Date >= '{startDate}'";
                    if (!string.IsNullOrEmpty(endDate)) query += $" AND Date <= '{endDate}'";
                    if (!string.IsNullOrEmpty(henhouseName) && henhouseName != "请选择") query += $" AND HenhouseName = '{henhouseName}'";

                    SqlDataAdapter sda = new SqlDataAdapter(query, conn);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);

                    dgvHistoryData.DataSource = dt;
                    DBConnection.Close(conn);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading data: " + ex.Message);
            }
        }

        private void LoadHenhouseNames()
        {
            try
            {
                using (SqlConnection conn = DBConnection.CreateConnection())
                {
                    DBConnection.Open(conn);
                    SqlDataAdapter sda = new SqlDataAdapter("SELECT DISTINCT HenhouseName FROM InternalEnvironment", conn);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    DataRow row = dt.NewRow();
                    row["HenhouseName"] = "请选择";
                    dt.Rows.InsertAt(row, 0);
                    cboHenhouse.DataSource = dt;
                    cboHenhouse.DisplayMember = "HenhouseName";
                    cboHenhouse.ValueMember = "HenhouseName";
                    DBConnection.Close(conn);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading henhouse names: " + ex.Message);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string startDate = txtStartDate.Text;
            string endDate = txtEndDate.Text;
            string henhouseName = cboHenhouse.SelectedValue.ToString();
            LoadData(startDate, endDate, henhouseName);
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvHistoryData.SelectedRows.Count > 0)
            {
                try
                {
                    int recordID = (int)dgvHistoryData.SelectedRows[0].Cells["RecordID"].Value;
                    DialogResult dialogResult = MessageBox.Show($"确定要删除{recordID}号记录吗？", "提示", MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.No)
                        return;

                    using (SqlConnection conn = DBConnection.CreateConnection())
                    {
                        string deleteCmdText = $"DELETE FROM InternalEnvironment WHERE RecordID = {recordID}";
                        SqlCommand command = new SqlCommand(deleteCmdText, conn);
                        DBConnection.Open(conn);
                        int rows = command.ExecuteNonQuery();
                        DBConnection.Close(conn);
                        if (rows > 0)
                        {
                            MessageBox.Show("记录删除成功", "提示");
                            LoadData();
                        }
                        else
                        {
                            MessageBox.Show("记录删除失败", "提示");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error deleting data: " + ex.Message);
                }
            }
        }

        private void BtnBack_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
